//
//  HMStatusViewModel.swift
//  WeiBo
//
//  Created by Feng on 2017/6/8.
//  Copyright © 2017年 feng. All rights reserved.
//

import UIKit
import YYModel
import SDWebImage

class HMStatusViewModel: NSObject {

//    var statusModelArray: [HMStatus] = [HMStatus]()
    var statusViewModelArray: [HMStatusCellViewModel] = [HMStatusCellViewModel]()
    
    //MARK: --加载当前登录用户及其关注的微博信息
    func loadData(isUp: Bool, callBack:@escaping (Bool,String)->())
    {
        let token = HMUserAccountViewModel.sharedUserAccount.userAccount?.access_token
        
        //上拉加载数据时,确定的微博id
        var maxId: Int64 = 0
        //下拉刷新时,初始id
        var sinceId: Int64 = 0
        
        if isUp
        {
            maxId = statusViewModelArray.last?.status?.id ?? 0
            
            //解决微博数据重复问题
            if maxId > 0
            {
                maxId -= 1
            }
        }
        else
        {
            sinceId = statusViewModelArray.first?.status?.id ?? 0
        }
        
        var message: String = "没有加载到微博数据"
        
        //  检查本地缓存数据
        let statusDicArray = HMStatusDALViewModel.checkCacheData(maxid: maxId, sinceid: sinceId)
        if statusDicArray.count > 0
        {
            let statusModelArray = NSArray.yy_modelArray(with: HMStatus.self, json: statusDicArray) as! [HMStatus]
            
            //将模型数组赋值给viewModel 的一个属性
            var tempArray = [HMStatusCellViewModel]()
            
            for model in statusModelArray
            {
                let viewModel = HMStatusCellViewModel()
                
                viewModel.status = model
                
                tempArray.append(viewModel)
            }
            
            if isUp
            {
                //将新请求到的数据添加到数组后面
                self.statusViewModelArray.append(contentsOf: tempArray)
            }
            else
            {
                self.statusViewModelArray.insert(contentsOf: tempArray, at: 0)
            }
            
            if tempArray.count > 0
            {
                message = "加载了\(tempArray.count)条微博数据"
            }

            callBack(true,message)
            return
        }
        
        //  代码执行到此没有缓存数据从网络加载微博数据
        NetworkTools.shareTools.requestStatus(accessToken: token!, maxId: maxId, sinceId: sinceId) { (response, error) in
            
            if error != nil
            {
                print("首页加载出错: \(error!)")
                //出错闭包回调
                callBack(false,message)
                
                return
            }
            
            //字典转模型
//            print(response ?? "无内容")
            //第一层级字典
            let res: [String: Any] = response as! [String: Any]
            //第二层级statuses 数组字典
            let statuses: [[String: Any]] = res["statuses"] as! [[String: Any]]
            
            //  缓存微博数据到本地
            HMStatusDALViewModel.cacheData(statusDicArray: statuses)
            
            let statusModelArray = NSArray.yy_modelArray(with: HMStatus.self, json: statuses) as! [HMStatus]
            
            //将模型数组赋值给viewModel 的一个属性
            var tempArray = [HMStatusCellViewModel]()
            
            //创建调度组
            let group = DispatchGroup()
            
            for model in statusModelArray
            {
                let viewModel = HMStatusCellViewModel()
                
                viewModel.status = model
                
                tempArray.append(viewModel)
                
                //判断原始微博图片数量
                if model.pic_urls?.count == 1
                {
                    //把任务添加到调度组
                    group.enter()
                    
                    let url = URL(string: (model.pic_urls?.last?.thumbnail_pic)!)
                    //图片存入沙盒
                    SDWebImageManager.shared().loadImage(with: url, options: [], progress: nil, completed: { (image, imageData, error, _, _, url) in
                        
                        //下载完成,离开队列
                        group.leave()
                    })
                }
                
                //判断转发微博图片数量
                if model.retweeted_status?.pic_urls?.count == 1
                {
                    //把任务添加到调度组
                    group.enter()
                    
                    let url = URL(string: (model.retweeted_status?.pic_urls?.last?.thumbnail_pic)!)
                    //图片存入沙盒
                    SDWebImageManager.shared().loadImage(with: url, options: [], progress: nil, completed: { (image, imageData, error, _, _, url) in
                        
                        //下载完成,离开队列
                        group.leave()
                    })
                }
            }
            
//            self.statusViewModelArray = tempArray
            
            if isUp
            {
                //将新请求到的数据添加到数组后面
                self.statusViewModelArray.append(contentsOf: tempArray)
            }
            else
            {
                self.statusViewModelArray.insert(contentsOf: tempArray, at: 0)
            }
            
            if tempArray.count > 0
            {
                message = "加载了\(tempArray.count)条微博数据"
            }
            
            //正确闭包回调--->在组队列中的任务全部执行完成后
            group.notify(queue: DispatchQueue.main, execute: { 
                callBack(true,message)
            })
        }
    }
}
